package _interview100;

import java.util.ArrayList;
import java.util.List;

/**
 * 22. 括号生成
 */
public class No22 {
    private List<String> ans;
    private StringBuilder path;
    private int n;

    public List<String> generateParenthesis(int n) {
        ans = new ArrayList<>();
        path = new StringBuilder();
        this.n = n;
        dfs(0, 0, 0);

        return ans;
    }

    private void dfs(int i, int l, int r) {
        if (l > n || r > l) return;
        if (path.length() == n * 2) {
            ans.add(path.toString());
            return;
        }
        path.append('(');
        dfs(i + 1, l + 1, r);
        path.deleteCharAt(i);
        path.append(')');
        dfs(i + 1, l, r + 1);
        path.deleteCharAt(i);
    }
}
